import { Response } from 'express';
import { Car } from '@/models/Vehicle';
import { AuthenticatedRequest } from '@/middleware/auth';

/**
 * @swagger
 * /api/cars:
 *   post:
 *     summary: 车辆录入
 *     tags: [车辆]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/CreateCarRequest'
 *     responses:
 *       201:
 *         description: 创建成功
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/CarSuccessResponse'
 *       400:
 *         description: 请求参数错误
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
export const createCar = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const {
      name,
      category,
      brand,
      carModel,
      productionTime,
      purchaseTime,
      vehicleType,
      licensePlate,
      notes,
      currentMileage,
      fuelCapacity,
      fuelType,
      purchasePrice,
      currency,
      batteryCapacity,
      mileage,
    } = req.body;

    // 数据验证
    if (
      !name ||
      !category ||
      !brand ||
      !carModel ||
      !productionTime ||
      !purchaseTime ||
      !vehicleType
    ) {
      res.status(400).json({
        success: false,
        message: '缺少必填字段',
        required: [
          'name',
          'category',
          'brand',
          'carModel',
          'productionTime',
          'purchaseTime',
          'vehicleType',
        ],
      });
      return;
    }

    // 验证车类型和燃油类型的匹配
    if (vehicleType === 'electric' && fuelType && fuelType !== '电') {
      res.status(400).json({
        success: false,
        message: '电车只能选择电动燃油类型',
      });
      return;
    }

    if ((vehicleType === 'fuel' || vehicleType === 'motor') && !fuelType) {
      res.status(400).json({
        success: false,
        message: '燃油车必须指定燃油类型',
      });
      return;
    }

    if (vehicleType === 'electric' && !batteryCapacity) {
      res.status(400).json({
        success: false,
        message: '电车必须指定电池容量',
      });
      return;
    }

    // 验证数值字段
    if (productionTime && isNaN(Number(productionTime))) {
      res.status(400).json({
        success: false,
        message: '生产时间必须是有效的时间戳',
      });
      return;
    }

    if (purchaseTime && isNaN(Number(purchaseTime))) {
      res.status(400).json({
        success: false,
        message: '购买时间必须是有效的时间戳',
      });
      return;
    }

    if (
      currentMileage &&
      (isNaN(Number(currentMileage)) || Number(currentMileage) < 0)
    ) {
      res.status(400).json({
        success: false,
        message: '当前里程必须是有效的非负数',
      });
      return;
    }

    const car = new Car({
      userId: req.userId,
      name,
      category,
      brand,
      carModel,
      productionTime: Number(productionTime),
      purchaseTime: Number(purchaseTime),
      vehicleType,
      licensePlate,
      notes,
      currentMileage: currentMileage ? Number(currentMileage) : undefined,
      fuelCapacity: fuelCapacity ? Number(fuelCapacity) : undefined,
      fuelType,
      purchasePrice: purchasePrice ? Number(purchasePrice) : undefined,
      currency,
      batteryCapacity: batteryCapacity ? Number(batteryCapacity) : undefined,
      mileage: mileage ? Number(mileage) : undefined,
    });

    await car.save();

    res.status(201).json({
      success: true,
      message: '车辆创建成功',
      data: car,
    });
  } catch (error) {
    console.error('createCar error:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
    });
  }
};

/**
 * @swagger
 * /api/cars:
 *   get:
 *     summary: 获取车辆列表
 *     tags: [车辆]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 10
 *         description: 每页数量
 *       - in: query
 *         name: category
 *         schema:
 *           type: string
 *         description: 车辆类型筛选
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/CarListResponse'
 */
export const getCars = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { page = 1, limit = 10, category } = req.query;
    const skip = (Number(page) - 1) * Number(limit);

    const filter: any = { userId: req.userId };
    if (category) {
      filter.category = category;
    }

    const cars = await Car.find(filter)
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(Number(limit));

    const total = await Car.countDocuments(filter);

    res.status(200).json({
      success: true,
      message: '获取车辆列表成功',
      data: {
        cars,
        pagination: {
          page: Number(page),
          limit: Number(limit),
          total,
          totalPages: Math.ceil(total / Number(limit)),
        },
      },
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
    });
  }
};

/**
 * @swagger
 * /api/cars/{id}:
 *   get:
 *     summary: 获取车辆详情
 *     tags: [车辆]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 车辆ID
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/CarSuccessResponse'
 *       404:
 *         description: 车辆不存在
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
export const getCarById = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { id } = req.params;

    const car = await Car.findOne({ _id: id, userId: req.userId });
    if (!car) {
      res.status(404).json({
        success: false,
        message: '车辆不存在',
      });
      return;
    }

    res.status(200).json({
      success: true,
      message: '获取车辆详情成功',
      data: car,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
    });
  }
};

/**
 * @swagger
 * /api/cars/{id}:
 *   put:
 *     summary: 更新车辆信息
 *     tags: [车辆]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 车辆ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/UpdateCarRequest'
 *     responses:
 *       200:
 *         description: 更新成功
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/CarSuccessResponse'
 *       404:
 *         description: 车辆不存在
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
export const updateCar = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { id } = req.params;
    const updateData = req.body;

    // 移除不允许更新的字段
    delete updateData.userId;
    delete updateData.category;
    delete updateData.productionTime;
    delete updateData.purchaseTime;

    const car = await Car.findOneAndUpdate(
      { _id: id, userId: req.userId },
      updateData,
      { new: true, runValidators: true }
    );

    if (!car) {
      res.status(404).json({
        success: false,
        message: '车辆不存在',
      });
      return;
    }

    res.status(200).json({
      success: true,
      message: '更新车辆信息成功',
      data: car,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
    });
  }
};

/**
 * @swagger
 * /api/cars/{id}:
 *   delete:
 *     summary: 删除车辆
 *     tags: [车辆]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 车辆ID
 *     responses:
 *       200:
 *         description: 删除成功
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/SuccessResponse'
 *       404:
 *         description: 车辆不存在
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
export const deleteCar = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { id } = req.params;

    const car = await Car.findOneAndDelete({
      _id: id,
      userId: req.userId,
    });
    if (!car) {
      res.status(404).json({
        success: false,
        message: '车辆不存在',
      });
      return;
    }

    // TODO: 删除车辆相关的所有记录（费用、收入、保养、维修、加油、充电记录）

    res.status(200).json({
      success: true,
      message: '删除车辆成功',
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
    });
  }
};
